<template>
  <div class="chart" v-resize="resizeCharts" ref="barChart"></div>
</template>
<script>
import * as echarts from 'echarts'
import Vue from 'vue'

export default {
  name: 'chartGraph',
  props: {
    data: { // graph
      type: String,
      default () {
        return ''
      }
    },
    otherTech: {
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      charts: null,
      time: 0,
      // graph: require('../data/map.json'),
      // graph: require('../data/force.json'),
      techMap: {
        1: '总体',
        2: '压气机',
        3: '燃烧'
      },
      tech: require('../data/tech.json'),
      graph: {},
      nodeVisible: {},
      nodeStatus: {}, // true-> open. false-> close
      keywordsAndPaper: [],
      links: [],
      nodes: [],
      sizeList: [120, 80, 60, 40, 20, 10, 10],
      categories: [
        '学科方向',
        '技术族',
        '技术类',
        '技术点',
        '文章',
        '关键词'
      ],
      initFlag: false
    }
  },
  computed: {},
  methods: {
    resizeCharts () {
      this.charts.resize()
    },
    initCharts () {
      this.$nextTick(() => {
        this.charts = echarts.init(this.$refs.barChart)
        this.charts.clear()

        this.charts.showLoading()
        // if (this.data === '1') {
        //   this.type = '总体'
        // } else if (this.data === '2') {
        //   this.type = '压气机'
        // } else if (this.data === '3') {
        //   this.type = '燃烧'
        // } else {
        //   console.log('empty type')
        //   return
        // }
        // Vue.prototype.post('/show_techpage', {
        //   type: this.type
        // }, this.techPageDataSucc)
        // this.nodes = []
        // this.links = []
        // this.nodeStatus = {}
        // this.tech = require('@/data/newTechPage.json')
        // this.$emit('update:otherTech', this.tech)
        // this.graph = this.tech.graph
        // if (this.graph.nodes.length <= 0) {
        //   this.$message.error('请求异常，请刷新重试')
        //   return
        // }
        // console.log('nodes foreach begin')
        // this.graph.nodes.forEach(item => {
        //   // this.nodeVisible[item.id] = false
        //   item.symbolSize = this.sizeList[item.category]
        //   this.nodeStatus[item.id] = false
        //   if (item.type === 'root') {
        //     this.nodes.push(item)
        //     // this.nodeVisible[item.id] = true
        //   }
        // })
        // console.log('nodes foreach end')
        // this.setOption()
      })
    },
    techPageDataSucc (res) {
      console.log('tech:', res.data)
      this.nodes = []
      this.links = []
      this.nodeStatus = {}
      this.tech = res.data
      this.$emit('update:otherTech', this.tech)
      this.graph = res.data.graph
      if (this.graph.nodes.length <= 0) {
        this.$message.error('请求异常，请刷新重试')
        return
      }
      console.log('nodes foreach begin')
      this.graph.nodes.forEach(item => {
        // this.nodeVisible[item.id] = false
        item.symbolSize = this.sizeList[item.category]
        this.nodeStatus[item.id] = false
        if (item.type === 'root') {
          this.nodes.push(item)
          // this.nodeVisible[item.id] = true
        }
      })
      // 增加一个initOpenNode(str)函数,用来初始化展开的节点，str中为‘总体-A-B-C'
      // 通过-切割，以此匹配名字找到所有关键节点存入数组waitOpen，然后遍历waitOpen依次changeStatus打开节点
      console.log('nodes foreach end')
      this.setOption()
    },
    setOption () {
      // 初始化
      var _this = this
      const option = this.getOption()
      this.charts.hideLoading()
      this.charts.setOption(option, true)
      this.charts.off('click')
      this.charts.off('dblclick')
      this.charts.on('click', function (params) {
        var that = this
        // 开启定时器，300ms的间隔区分单击和双击，解决双击时执行两次单击事件
        clearTimeout(that.time)
        that.time = setTimeout(() => {
          // 写单击事件执行的逻辑代码
          console.log('click!')
          if (params.dataType === 'node') {
            // console.log('Single Click:', params)
            const cate = params.data.category
            if (cate !== 4 && cate !== 5) {
              var name = params.data.name
              _this.changeOtherTech(name)
            }
          }
        }, 500)
      })
        .on('dblclick', function (params) {
          clearTimeout(this.time)
          console.log('double click!')
          if (params.dataType === 'node') {
            // var name = params.data.name
            var id = params.data.id
            // console.log('Node:', name)
            _this.changeStatus(id)
            const option = _this.getOption()
            _this.charts.setOption(option, true)
          }
        })

      // eslint-disable-next-line no-unused-vars
      // function openNode (nodeId) {
      //   if(this.nodeSt)
      // }
    },
    changeOtherTech (name) {
      this.$message.success('重新加载图表数据中...')
      // this.$axios
      //   .get('http://localhost:2226/get_bar_line?type=' + encodeURI(this.type) + '&name=' + encodeURI(name))
      //   .then(res => {
      //     // console.log('tech:', res.data)
      //     this.tech = res.data
      //     this.$emit('update:otherTech', this.tech)
      //   })
      //   .catch(error => {
      //     console.log('error:', error)
      //     this.$message.error('请求错误')
      //   })
      Vue.prototype.post('http://192.168.0.94:2226/get_bar_line', {
        type: this.type,
        name: name
      }, this.barLineDataSucc)
    },
    barLineDataSucc (res) {
      this.tech = res.data
      this.$emit('update:otherTech', this.tech)
    },
    changeStatus (nodeId) {
      // console.log('ready to change id=', nodeId)
      if (this.nodeStatus[nodeId]) {
        this.nodeClose(nodeId)
      } else {
        this.nodeOpen(nodeId)
      }
      // console.log('new nodes:', this.nodes)
      // console.log('new links:', this.links)
    },
    addNode (nodeId) {
      // console.log('addNode:', nodeId)
      let flag = true
      this.graph.nodes.forEach(item => {
        if (flag && item.id === nodeId) {
          if (this.nodes.indexOf(item) < 0) {
            this.nodes.push(item)
            flag = false
          }
        }
      })
    },
    removeNode (nodeId) {
      // console.log('remove node:', nodeId)
      // var newNodes = JSON.parse(JSON.stringify(this.nodes))
      // this.nodes = []
      // console.log('temp:', newNodes)
      // newNodes.forEach(item => {
      //   if (item.id !== nodeId) {
      //     this.nodes.push(JSON.parse(JSON.stringify(item)))
      //   }
      // })
      // console.log('update nodes:', this.nodes)
      // console.log('remove:', nodeId)
      this.nodes.forEach(item => {
        if (item.id === nodeId) {
          this.nodes.splice(this.nodes.indexOf(item), 1)
        }
      })
    },
    nodeOpen (nodeId) {
      console.log('open:', nodeId)
      this.nodeStatus[nodeId] = true
      let flag = true
      this.graph.links.forEach(item => {
        // console.log('check link:', item)
        if (item.source === nodeId) {
          flag = false
          this.links.push(item)
          this.addNode(item.target)
        }
      })
      if (flag) {
        this.nodeStatus[nodeId] = false
      }
    },
    nodeClose (nodeId) {
      console.log('Close:', nodeId)
      this.nodeStatus[nodeId] = false
      for (var i = this.links.length - 1; i >= 0; i--) {
        const source = this.links[i].source
        const target = this.links[i].target

        if (source === nodeId) {
          // console.log('delete ', source, ' to ', target)
          this.links.splice(i, 1)
          this.removeNode(target)
          if (this.nodeStatus[target] === true) {
            this.nodeClose(target)
          }
        }
      }
      // this.links.forEach(item => {
      //   if (item.source === nodeId) {
      //     this.links.splice(this.links.indexOf(item), 1)
      //     this.removeNode(item.target)
      //     if (this.nodeStatus[item.target] === true) {
      //       this.nodeClose(item.target)
      //     }
      //   }
      // })
    },
    handlerDataSucc (res) {
      console.log('handler begin')
      this.nodes = []
      this.links = []
      this.nodeStatus = {}
      // this.setOption()
      // const _this = this
      // _this.nodes = []
      // _this.links = []
      // _this.nodeStatus = {}
      // _this.setOption()
      this.tech = res.data
      this.$emit('update:otherTech', this.tech)

      this.graph = res.data.graph
      if (this.graph.nodes.length <= 0) {
        this.$message.error('更新异常，请刷新重试')
        return
      }
      this.graph.nodes.forEach(item => {
        // this.nodeVisible[item.id] = false
        item.symbolSize = this.sizeList[item.category]
        this.nodeStatus[item.id] = false
        if (item.type === 'root') {
          this.nodes.push(item)
        }
      })
      // _this.setOption()
      this.setOption()
      console.log('handler end')
    },
    getOption () {
      // console.log('getOption, nodes:', this.nodes)
      const option = {
        // title: {
        //   text: '图谱',
        //   subtext: 'Default layout',
        //   top: 'bottom',
        //   left: 'right'
        // },
        tooltip: {
          trigger: 'item',
          enterable: true,
          formatter: function (params) { // 连接线上提示文字格式化
            // if (params.data.source) { // 注意判断，else是将节点的文字也初始化成想要的格式
            //   // return params.data.source + '->' + params.data.target
            //   return params.data.type
            // } else {
            //   return params.name
            // }
            if (params.dataType === 'node' && params.data.category === 3) {
              console.log('cur node:', params)
              var htmlStr = '<div style="height: auto;max-height: 240px;overflow-y: auto;"><p><B>' + params.data.name + '-关键词</B></p><br/>'
              params.data.keywords.forEach(item => {
                htmlStr += '<p style="margin:0;line-height: 20%;">' + item + '</p></br>'
              })
              htmlStr = htmlStr + '<p><B>' + params.data.name + '-相关文献</B></p>'
              params.data.papers.forEach(item => {
                const url = 'http://192.168.1.1:8080/get_qh_detail?tm=' + encodeURI(item.tm) + '&wjm=' + encodeURI(item.wjm) +
                  '&bm=' + encodeURI(item.bm) + '&tablename=' + encodeURI(item.tablename + '&db=' + item.db)
                // htmlStr += '<a href=\'' + url + encodeURI(item.id) + '\' target="_blank">' + item.title + '</a></br>'
                htmlStr += '<a href=\'' + url + '\' target="_blank">' + item.title + '</a></br>'
              })
              // for (var i = 0; i < 50; i++) {
              //   htmlStr += '<p style="color: #666;">' + 'ceshi' + i + '</p>'
              // }
              htmlStr += '</div>'
              return htmlStr
            } else {
              return ''
            }
          }

        },
        legend: [
          {
            // selectedMode: 'single',
            data: this.categories.map(function (a) {
              return a.name
            })
          }
        ],
        color: ['#99BBFF', '#00BBFF', '#77DDFF', '#33FFAA', '#CCCCFF'],
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            name: 'Les Miserables',
            type: 'graph',
            layout: 'force',
            // data: this.graph.nodes,
            // links: this.graph.links,
            data: this.nodes,
            links: this.links,
            categories: this.categories,
            roam: true,
            draggable: true,
            force: {
              edgeLength: 200,
              repulsion: 1000,
              gravity: 0.1
            },
            label: {
              show: true,
              // position: 'right',
              formatter: '{b}',
              // width: 100,
              overflow: 'truncate'
            },
            lineStyle: {
              color: 'source'
              // curveness: 0.3,
              // width: 20
            },
            emphasis: {
              focus: 'adjacency',
              lineStyle: {
                width: 10
              }
            }
          }
        ]
      }
      return option
    }
  },
  mounted () {
    this.initCharts()
  },
  beforeDestroy () {
    this.charts && this.charts.dispose()
    this.charts = null
  },
  watch: {
    data: {
      handler () {
        // const _this = this
        // _this.nodes = []
        // _this.links = []
        // _this.nodeStatus = {}
        // _this.setOption()
        // console.log('dataIndex Change to: ', this.data)
        if (this.data === '1') {
          this.type = '总体'
        } else if (this.data === '2') {
          this.type = '压气机'
        } else {
          this.type = '燃烧'
        }
        // this.$axios
        //   .get('http://localhost:2226/show_techpage?type=' + encodeURI(this.type))
        //   .then(res => {
        //     // console.log('update tech in page2:', res.data)
        //     this.tech = res.data
        //     this.$emit('update:otherTech', this.tech)
        //
        //     this.graph = this.tech.graph
        //     this.graph.nodes.forEach(item => {
        //       // this.nodeVisible[item.id] = false
        //       item.symbolSize = this.sizeList[item.category]
        //       this.nodeStatus[item.id] = false
        //       if (item.type === 'root') {
        //         this.nodes.push(item)
        //         // this.nodeVisible[item.id] = true
        //       }
        //     })
        //     _this.setOption()
        //   })
        //   .catch(error => {
        //     console.log('error:', error)
        //     this.$message.error('请求错误')
        //   })
        Vue.prototype.post('http://192.168.0.94:2226/show_techpage', {
          "type": this.type
        }, this.handlerDataSucc)
      }
    }
  },
  components: {}
}
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
